package com.ruoyi.business.controller;

import java.util.List;
import java.util.stream.Collectors;

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.business.domain.Category;
import com.ruoyi.business.service.ICategoryService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * CategoryController
 *
 * @author win
 * @date 2021-06-14
 */
@RestController
@RequestMapping("/Category/category")
@Slf4j
public class CategoryController extends BaseController
{
    @Autowired
    private ICategoryService categoryService;

    /**
     * 查询Category列表
     */
//    @PreAuthorize("@ss.hasPermi('Category:category:list')")
    @GetMapping("/list")
    public TableDataInfo list(Category category)
    {
        startPage();
        List<Category> list = categoryService.selectCategoryList(category);
        list.forEach(item -> {
            Category parent = categoryService.selectCategoryById(item.getParentId());
            if (parent != null) {
                item.setParentName(parent.getTitle());
            }
        });
        return getDataTable(list);
    }

    /**
     * 导出Category列表
     */
//    @PreAuthorize("@ss.hasPermi('Category:category:export')")
    @Log(title = "Category", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(Category category)
    {
        List<Category> list = categoryService.selectCategoryList(category);
        ExcelUtil<Category> util = new ExcelUtil<Category>(Category.class);
        return util.exportExcel(list, "Category数据");
    }

    /**
     * 获取Category详细信息
     */
//    @PreAuthorize("@ss.hasPermi('Category:category:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(categoryService.selectCategoryById(id));
    }

    /**
     * 新增Category
     */
//    @PreAuthorize("@ss.hasPermi('Category:category:add')")
    @Log(title = "Category", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Category category)
    {
        if ( category.getPosition() ==  1) {
            // 1 为主导航栏的位置编码
            Integer num = categoryService.countCategories(1);
            if ( num >= 9 ) {
                return AjaxResult.error("主导航栏最多只能添加9个顶级栏目，请检查主导航栏顶级栏目的数量");
            }
        }
        return toAjax(categoryService.insertCategory(category));
    }

    /**
     * 修改Category
     */
//    @PreAuthorize("@ss.hasPermi('Category:category:edit')")
    @Log(title = "Category", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Category category)
    {
        if ( category.getPosition() == 1 && category.getStatus() == 1 ) {
            // 1 为主导航栏的位置编码
            Integer num = categoryService.countCategories(1);
            if ( num >= 9 ) {
                return AjaxResult.error("主导航栏最多只能展示9个顶级栏目，请检查主导航栏顶级栏目的状态");
            }
        }
        return toAjax(categoryService.updateCategory(category));
    }

    /**
     * 删除Category
     */
//    @PreAuthorize("@ss.hasPermi('Category:category:remove')")
    @Log(title = "Category", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(categoryService.deleteCategoryByIds(ids));
    }

    /**
     * 获取栏目树
     */
//    @PreAuthorize("@ss.hasPermi('business:category:list')")
    @GetMapping("/categoryTree")
    public AjaxResult categoryTree(Category category) {
        List<Category> allList =
                categoryService.selectCategoryList(new Category().setStatus(1));
        List<Category> indexList =
                categoryService.selectCategoryList(new Category().setParentId(0L).setStatus(1).setPosition(category.getPosition()));
        // 递归查询
        List<Category> resList = indexList.stream().map(item -> categoryService.queryTree(allList, item)).collect(Collectors.toList());
        return AjaxResult.success(resList);
    }
}
